package com.guandi.geekbrowser.Utils;

import com.alibaba.fastjson.JSONObject;
import com.guandi.geekbrowser.primary.entity.Details;
import com.guandi.geekbrowser.primary.entity.Ipool;
import com.guandi.geekbrowser.primary.entity.TaskItem;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.util.Base64;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

public class EasyUtil {

    private final static String XLS = "xls";
    private final static String XLSX = "xlsx";

    public static JSONObject getParam(String _str) {
        JSONObject _obj = new JSONObject();
        if (_str.contains("&")) {
            String[] _kv = _str.split("&");
            for (int i = 0; i < _kv.length; i++) {
                String[] split = _kv[i].split("=");
                _obj.put(split[0], split[1]);
            }
        } else {
            String[] _kv = _str.split("=");
            _obj.put(_kv[0], _kv[1]);
        }
        return _obj;
    }

    /**
     * 读入excel文件，解析后返回
     *
     * @param file
     * @throws IOException
     */
    public static List<Details> readExcel(MultipartFile file, String tabName, String userId, String country) throws IOException {
        //检查文件
        checkFile(file);
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
        List<Details> list = new ArrayList<>();
        if (workbook != null) {
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //获得当前行的开始列
                    int firstCellNum = row.getFirstCellNum();
                    //获得当前行的列数
//                    int lastCellNum = row.getPhysicalNumberOfCells();
                    int lastCellNum = row.getLastCellNum();
                    //赋值
                    //循环当前行
                    Details detail = new Details();
                    detail.setTabName(tabName);
                    detail.setUserId(userId);
                    detail.setCountry(country);
                    detail.setRegisterDate(new Date());
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        String cellValue = null;
                        try {
                            cellValue = getCellValue(cell);
                        } catch (Exception e) {
//                            e.printStackTrace();
                            break;
                        }
                        switch (cellNum) {
                            case 0:
                                detail.setAccount(cellValue);
                                break;
                            case 1:
                                detail.setPassword(cellValue);
                                break;
                            case 2:
                                detail.setMailPassword(cellValue);
                                break;
                            case 3:
                                detail.setPcCookie(cellValue);
                                break;
                        }
                    }
                    list.add(detail);
                }
            }
            workbook.close();
        }
        return list;
    }

    public static void checkFile(MultipartFile file) throws IOException {
        //判断文件是否存在
        if (null == file) {
            System.out.println("文件不存在！");
            throw new FileNotFoundException("文件不存在！");
        }
        //获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if (!fileName.endsWith(XLS) && !fileName.endsWith(XLSX)) {
            System.out.println(fileName + "不是excel文件");
            throw new IOException(fileName + "不是excel文件");
        }
    }

    public static Workbook getWorkBook(MultipartFile file) {
        //获得文件名
        String fileName = file.getOriginalFilename();
        //创建Workbook工作薄对象，表示整个excel
        Workbook workbook = null;
        try {
            //获取excel文件的io流
            InputStream is = file.getInputStream();
            //根据文件后缀名不同(XLS和XLSX)获得不同的Workbook实现类对象
            if (fileName.endsWith(XLS)) {
                //2003
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith(XLSX)) {
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return workbook;
    }

    public static String getCellValue(Cell cell) throws Exception {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //判断数据的类型
        switch (cell.getCellTypeEnum()) {
            case NUMERIC: //数字
                DecimalFormat df = new DecimalFormat("0");
                String format = df.format(cell.getNumericCellValue());
                cellValue = format;
                break;
            case STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case BLANK: //空值
                cellValue = "";
                break;
            case ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    /**
     * 导出Excel文件
     *
     * @param tabName
     */
    public static void exportExcel(String tabName, HttpServletResponse response, List<Details> detailsList) {
        //1.创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
//        XSSFWorkbook wbt = new XSSFWorkbook();
        //2.在建立的工作簿中添加一个sheet，对应Excell文件中的工作簿，并设置工作簿名称
        HSSFSheet sheet = wb.createSheet("我是工作簿左下角的名字（第一个）");
        //2.1如果需要多个，则继续创建即可
//        HSSFSheet sheet1 = wb.createSheet("我是工作簿左下角的名字（第二个）");


        //3.第一行2,3,4列合并（注意：从0开始开始，参数分别表示起始第2行，结束第4行，起始第2列，结束第4列，大家可以
        //在脑海中想象画出对应的矩形框）
//        CellRangeAddress region1 = new CellRangeAddress(1, 3, (short) 1, (short) 3);
        HSSFRow row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("账号");
        row1.createCell(1).setCellValue("密码");
        row1.createCell(2).setCellValue("邮箱密码");
//        row1.createCell(5).setCellValue("注册时间");
//        HSSFRow row2 = sheet.createRow(1);
//        row2.createCell(0).setCellValue("1@qq.com");
//        row2.createCell(1).setCellValue("asdasd");
//        row2.createCell(2).setCellValue("fsdfd");
//        row2.createCell(3).setCellValue("sadfs");
//        row2.createCell(4).setCellValue("US");
//        row2.createCell(5).setCellValue(new Date());
        if (detailsList != null & detailsList.size() > 0) {
            for (int i = 1; i <= detailsList.size(); i++) {
                HSSFRow row = sheet.createRow(i);
                Details detail = detailsList.get(i - 1);
                row.createCell(0).setCellValue(detail.getAccount());
                row.createCell(1).setCellValue(detail.getPassword());
                row.createCell(2).setCellValue(detail.getMailPassword());
            }
        }
//        //第一个合并单元区域：
//        //3.1为合并单元格赋值，实际就是为坐标（1,1）这个单元格赋值（工作簿中坐标是（2，2)）
//        //经本人测试，只有合并区域左上角那个单元格赋值能成功，左下角、右下角、右上角都不行。
//        //注意：这儿colum必须是 1 ：因为这是代码，是从0开始数的，Excel中对应的是2，以下同理
//        row1.createCell(1).setCellValue("第二至四行2-4列合并");
//        //4.把合并区域添加到工作簿中
//        sheet.addMergedRegion(region1);
//
//        //5.设置合并单元格的边框样式，用RegionUtil这个工具类
//
//        //5.1设置合并单元格的边r框是------o.........0r__________等等这样的样式
//        RegionUtil.setBorderBottom(BorderStyle.THIN, region1, sheet);
//        RegionUtil.setBorderLeft(BorderStyle.THIN, region1, sheet);
//        RegionUtil.setBorderRight(BorderStyle.THIN, region1, sheet);
//        RegionUtil.setBorderTop(BorderStyle.THIN, region1, sheet);
//
//        //5.2设置合并单元格边框的颜色
//        RegionUtil.setBottomBorderColor(12, region1, sheet);
//        RegionUtil.setLeftBorderColor(12, region1, sheet);
//        RegionUtil.setRightBorderColor(12, region1, sheet);
//        RegionUtil.setTopBorderColor(12, region1, sheet);

        //6.创建单元格（单个cell）样式（为合并的单元格设置样式，设计上就是合并单元格的最左上角
        //那个单元格设置样式，这儿坐标为（1.1），excel中为（2,2））这同时也是单个单元格的样式设置的代码
//        HSSFCellStyle cellStyle = wb.createCellStyle();
//        // 6.1创建字体样式对象
//        Font fontStyle = wb.createFont();
//        //6.1.1字体加粗
//        fontStyle.setBold(true);
//        //6.1.2字体大小
//        fontStyle.setFontHeightInPoints((short) 12);
//        // 7.将字体样式添加到单元格样式中
//        cellStyle.setFont(fontStyle);
//        // 6.2 单元格样式-->水平居中
//        cellStyle.setAlignment(HorizontalAlignment.CENTER);
//        //6.3 单元格样式-->垂直居中
//        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //6.4 单个cell边框样式
//        cellStyle.setBorderBottom(BorderStyle.THIN);
//        cellStyle.setBorderLeft(BorderStyle.THIN);
//        cellStyle.setBorderRight(BorderStyle.THIN);
//        cellStyle.setBorderTop(BorderStyle.THIN);
//        //6.4 单个cell框y、颜色
//        cellStyle.setLeftBorderColor((short) 12);
//        cellStyle.setBottomBorderColor((short) 12);
//        cellStyle.setRightBorderColor((short) 12);
//        cellStyle.setTopBorderColor((short) 12);

        //7.得到坐标（1,1）Excel中（2,2）这个单元格cell对象，设置样式
//        CellUtil.getCell(row1, 1).setCellStyle(cellStyle);

        try {
//            String fileName = "C:\\Users\\jack\\Desktop\\temp.xls";
            buildExcelDocument(tabName, wb, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("写出成功！");
    }

    /**
     * 导出点赞信息
     *
     * @param fileName
     * @param response
     * @param taskItemList
     */
    public static void exportLikeExcel(String fileName, HttpServletResponse response, List<TaskItem> taskItemList) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("默认");
        HSSFRow row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("点赞地址");
        row1.createCell(1).setCellValue("ASIN");
        row1.createCell(2).setCellValue("总次数");
        if (taskItemList != null & taskItemList.size() > 0) {
            for (int i = 1; i <= taskItemList.size(); i++) {
                HSSFRow row = sheet.createRow(i);
                TaskItem taskItem = taskItemList.get(i - 1);
                row.createCell(0).setCellValue(taskItem.getUrl());
                row.createCell(1).setCellValue(taskItem.getAsinCode());
                row.createCell(2).setCellValue(taskItem.getTotalCount());
            }
        }

        try {
//            String fileName = "C:\\Users\\jack\\Desktop\\temp.xls";
            buildExcelDocument(fileName, wb, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("写出成功！");
    }

    /**
     * 导入点赞信息
     *
     * @param file
     * @param userId
     * @return
     * @throws IOException
     */
    public static List<TaskItem> readLikeExcel(MultipartFile file, Integer type, String curTaskName, String userId) throws IOException {
        //检查文件
        checkFile(file);
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
        List<TaskItem> list = new ArrayList<>();
        if (workbook != null) {
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    int firstCellNum = row.getFirstCellNum();
                    int lastCellNum = row.getLastCellNum();
                    //赋值
                    //循环当前行
                    TaskItem taskItem = new TaskItem();
                    taskItem.setUserId(userId);
                    taskItem.setDate(new Date());
                    taskItem.setTaskName(curTaskName);
                    taskItem.setType(type);
                    taskItem.setFinishCount(0);
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        String cellValue = null;
                        try {
                            cellValue = getCellValue(cell);
                        } catch (Exception e) {
//                            e.printStackTrace();
                            break;
                        }
                        switch (cellNum) {
                            case 0:
                                taskItem.setUrl(cellValue);
                                break;
                            case 1:
                                taskItem.setAsinCode(cellValue);
                                break;
                            case 2:
                                double v = Double.parseDouble(cellValue);
                                int totalCount = (int) v;
                                taskItem.setTotalCount(totalCount);
                                break;
                        }
                    }
                    list.add(taskItem);
                }
            }
            workbook.close();
        }
        return list;
    }

    //生成excel文件
    public void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
        FileOutputStream fos = new FileOutputStream(filename);
        workbook.write(fos);
        fos.flush();
        fos.close();
    }

    //浏览器下载excel
    public static void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }


    /**
     * MD5方法
     *
     * @param text 明文
     * @return 密文
     * @throws Exception
     */
    public static String md5(String text) throws Exception {
        //加密后的字符串
        String encodeStr = DigestUtils.md5Hex(text);
//        System.out.println("MD5加密后的字符串为:encodeStr="+encodeStr);
        return encodeStr;
    }

    /**
     * MD5验证方法
     *
     * @param text 明文
     * @param md5  密文
     * @return true/false
     * @throws Exception
     */
    public static boolean verify(String text, String md5) throws Exception {
        //根据传入的密钥进行验证
        String md5Text = md5(text);
        if (md5Text.equalsIgnoreCase(md5)) {
            System.out.println("MD5验证通过");
            return true;
        }
        return false;
    }

    /**
     * Triple-DES 加密
     *
     * @param clearText
     * @return
     */
//    public static String encryptProperty(String clearText) {
//        //不能动,重要密钥
//        String KEY_STRING = "RRYa6li5NGFodgKUtvS1I6fZwY8xpJjI";
//
//        byte[] key = Base64.decode(KEY_STRING.getBytes());
//
//        return performDESCoder(clearText, key, true);
//    }

    /**
     * Triple-DES 解密
     * <p>
     * //     * @param cipherText
     *
     * @return
     */
//    public static String decryptProperty(String cipherText) {
//        //不能动,重要密钥
//        String KEY_STRING = "RRYa6li5NGFodgKUtvS1I6fZwY8xpJjI";
//
//        byte[] key = Base64.decode(KEY_STRING.getBytes());
//
//        return performDESCoder(cipherText, key, false);
//    }

//    /**
//     * Triple-DES 加解密操作
//     *
//     * @param inputValue
//     * @param key
//     * @param encrypt
//     * @return
//     */
//    public static String performDESCoder(String inputValue, byte[] key,
//                                         boolean encrypt) {
//        String rtnValue = "";
//
//        String KEY_ALGORITHM = "DESede";
//        String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
//
//        byte[] data = null;
//        try {
//            DESedeKeySpec dks = new DESedeKeySpec(key);
//
//            SecretKeyFactory keyFactory = SecretKeyFactory
//                    .getInstance(KEY_ALGORITHM);
//
//            SecretKey secretKey = keyFactory.generateSecret(dks);
//
//            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//
//            byte[] input = null;
//            if (encrypt) {
//                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//                input = inputValue.getBytes();
//            } else {
//                cipher.init(Cipher.DECRYPT_MODE, secretKey);
//                input = Base64.decode(inputValue.getBytes());
//            }
//            if (input != null) {
//                data = cipher.doFinal(input);
//            }
//        } catch (InvalidKeyException e) {
//            System.out.println(e.getMessage());
//        } catch (NoSuchAlgorithmException e) {
//            System.out.println(e.getMessage());
//        } catch (InvalidKeySpecException e) {
//            System.out.println(e.getMessage());
//        } catch (NoSuchPaddingException e) {
//            System.out.println(e.getMessage());
//        } catch (IllegalBlockSizeException e) {
//            System.out.println(e.getMessage());
//        } catch (BadPaddingException e) {
//            System.out.println(e.getMessage());
//        }
//
//        if (data == null) {
//            rtnValue = inputValue;
//        } else {
//            if (encrypt) {
//                rtnValue = new String(Base64
//                        .encode(data));
//            } else {
//                rtnValue = new String(data);
//            }
//        }
//
//        return rtnValue;
//    }
    public static boolean checkIp(String ip) {
        String regex = "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\" +
                ".(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])";

        // 匹配1 和匹配2均可实现Ip判断的效果
        // 匹配1 和匹配2均可实现Ip判断的效果
        Pattern pattern = Pattern.compile(regex);

        return pattern.matcher(ip).matches();
    }

    public static boolean checkPort(String port) {
//        String regex = "([0-65535])";
        String regex = "([0-9]|[1-9]\\d|[1-9]\\d\\d|[1-9]\\d\\d\\d|[1-5]\\d\\d\\d\\d|[6][0-4]\\d\\d\\d|[6][5][0-4]\\d\\d|[6][5][5][0-2]\\d|65535)";

        // 匹配1 和匹配2均可实现Ip判断的效果
        // 匹配1 和匹配2均可实现Ip判断的效果
        Pattern pattern = Pattern.compile(regex);

        return pattern.matcher(port).matches();
    }

    /**
     * 获取注册IP
     *
     * @param ip
     * @param port
     * @return
     * @throws Exception
     */
    public static String getRegisterIp(String ip, String port) {
        URL url = null;
        try {
            url = new URL("http://lumtest.com/myip.json");
        } catch (MalformedURLException e) {
            //e.printStackTrace();
            System.out.println(e.getMessage());
            return "";
        }
        // 创建代理服务器
        InetSocketAddress addr = new InetSocketAddress(ip, Integer.parseInt(port));
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        URLConnection conn = null;
        try {
            conn = url.openConnection(proxy);
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("错误信息:" + e.getMessage());
            return "";
        }
        InputStream in_st = null;
        try {
            in_st = conn.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(in_st));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while (true) {
                try {
                    if (!((line = in.readLine()) != null)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                buffer.append(line);
                return buffer.toString();
            }
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("错误信息:" + e.getMessage());
        }
        return null;
    }

    public static boolean testProxy(String path, String address, Integer port, String proxyUser, String proxyPassword) throws IOException {
        URL url = new URL(path);
        // /创建代理服务器
        InetSocketAddress addr = new InetSocketAddress(address, port);
        // Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); // Socket 代理
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
        if (!isEmpty(proxyUser) && !isEmpty(proxyPassword)) {
            Authenticator.setDefault(new MyAuthenticator(proxyUser, proxyPassword));// 设置代理的用户和密码
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);// 设置代理访问
        InputStreamReader in = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(in);
        while (true) {
            String s = reader.readLine();
            if (s != null) {
                System.out.println(s);
                return s.contains("html");
            } else {
                return false;
            }
        }
    }


//    Authenticator.setDefault(new MyAuthenticator("username", "password"));

    public static class MyAuthenticator extends Authenticator {
        private String user = "";
        private String password = "";

        public MyAuthenticator(String user, String password) {
            this.user = user;
            this.password = password;
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }
    }

    public static boolean refreshIp(String address, String port) {
        String url = "http://" + address + ":22999/api/refresh_sessions/" + port;
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        try {
            BasicNameValuePair nameValuePairRRows = new BasicNameValuePair("port", port);
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(nameValuePairRRows);
            UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(list, "utf-8");
            post.setEntity(urlEntity);
            HttpResponse response = client.execute(post);
            String reg = "2[0-9][0-9]";
            int statusCode = response.getStatusLine().getStatusCode();
            boolean matches = Integer.toString(statusCode).matches(reg);
            return matches;
        } catch (ClientProtocolException e) {
//            e.printStackTrace();
            System.out.println(e.getMessage());
            return false;
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println(e.getMessage());
            return false;
        }
    }

    public static boolean isEmpty(String str) {
        if (StringUtils.isEmpty(str) || StringUtils.isBlank(str)) {
            return true;
        } else {
            return false;
        }
    }

    public static List<Ipool> readIPExcel(MultipartFile file, Integer type, String userId, String country) {
        //检查文件
        try {
            checkFile(file);
        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("检查文件出错" + e.getMessage());
        }
        //获得Workbook工作薄对象
        Workbook workbook = getWorkBook(file);
        //创建返回对象，把每行中的值作为一个数组，所有行作为一个集合返回
        List<Ipool> list = new ArrayList<>();
        if (workbook != null) {
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                //获得当前sheet工作表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //获得当前sheet的开始行
                int firstRowNum = sheet.getFirstRowNum();
                //获得当前sheet的结束行
                int lastRowNum = sheet.getLastRowNum();
                //循环除了第一行的所有行
                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                    //获得当前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //获得当前行的开始列
                    int firstCellNum = row.getFirstCellNum();
                    //获得当前行的列数
//                    int lastCellNum = row.getPhysicalNumberOfCells();
                    int lastCellNum = row.getLastCellNum();
                    //赋值
                    //循环当前行
                    Ipool ipool = new Ipool();
                    ipool.setType(type);
                    ipool.setUserId(userId);
                    ipool.setUsestatus(0);
                    ipool.setBind(0);
                    ipool.setCountry(country);
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        String cellValue = null;
                        try {
                            cellValue = getCellValue(cell);
                        } catch (Exception e) {
//                            e.printStackTrace();
                            break;
                        }
                        switch (cellNum) {
                            case 0:
                                ipool.setAddress(cellValue);
                                break;
                            case 1:
                                ipool.setPort(cellValue);
                                break;
                            case 2:
                                ipool.setProxyUser(cellValue);
                                break;
                            case 3:
                                ipool.setProxyPassword(cellValue);
                                break;
                        }
                    }
                    list.add(ipool);
                }
            }
            try {
                workbook.close();
            } catch (IOException e) {
//                e.printStackTrace();
                System.out.println("workbook关闭异常!" + e.getMessage());
            }
        }
        return list;
    }
}
